<template>
  <div class="login-container">
    <div class="artistic-card" :class="{ 'show-register-panel': showRegister }"
         @mousemove="handleCardMouseMove" @mouseleave="resetCardTransform">
      <!-- 卡片头部 -->
      <div class="card-header">
        <h1 v-if="!showRegister">欢迎来到 <span class="gradient-text">艺语</span></h1>
        <h1 v-else>注册 <span class="gradient-text">艺语</span></h1>
        <p v-if="!showRegister">体验沉浸式艺术交流</p>
        <p v-else>加入艺廊，创作您的数字身份</p>
      </div>

      <!-- 卡片主体：登录或注册表单 -->
      <div class="card-body">
        <div class="form-container">
          <!-- 登录表单 -->
          <form @submit.prevent="handleLogin" v-if="!showRegister" class="form-panel active-panel">
            <div class="input-group">
              <input
                  type="text"
                  v-model="loginForm.username"
                  placeholder="用户名"
                  class="artistic-input"
                  required
              >
              <i class="icon fas fa-user"></i>
            </div>

            <div class="input-group">
              <input
                  type="password"
                  v-model="loginForm.password"
                  placeholder="密码"
                  class="artistic-input"
                  required
              >
              <i class="icon fas fa-lock"></i>
            </div>

            <button
                type="submit"
                class="artistic-button"
                :disabled="isLoading"
            >
              <span v-if="isLoading" class="spinner"></span>
              <span v-else>进入艺廊</span>
            </button>
          </form>

          <!-- 注册表单 -->
          <form @submit.prevent="handleRegister" v-else class="form-panel active-panel">
            <div class="input-group">
              <input
                  type="text"
                  v-model="registerForm.username"
                  placeholder="设置用户名"
                  class="artistic-input"
                  required
              >
              <i class="icon fas fa-user-shield"></i>
            </div>

            <div class="input-group">
              <input
                  type="text"
                  v-model="registerForm.nickname"
                  placeholder="设置昵称"
                  class="artistic-input"
                  required
              >
              <i class="icon fas fa-signature"></i>
            </div>

            <div class="input-group">
              <input
                  type="password"
                  v-model="registerForm.password"
                  placeholder="设置密码"
                  class="artistic-input"
                  required
              >
              <i class="icon fas fa-key"></i>
            </div>

            <div class="input-group">
              <input
                  type="password"
                  v-model="registerForm.confirmPassword"
                  placeholder="确认密码"
                  class="artistic-input"
                  required
              >
              <i class="icon fas fa-check-double"></i>
            </div>

            <button
                type="submit"
                class="artistic-button register"
                :disabled="isLoading"
            >
              <span v-if="isLoading" class="spinner"></span>
              <span v-else>立即注册</span>
            </button>
          </form>

          <!-- 错误/成功提示 -->
          <div v-if="errorMessage"
               class="message-display-box"
               :class="{ 'success-message-box': isSuccessMessage, 'error-message-box': !isSuccessMessage }">
            <i :class="isSuccessMessage ? 'fas fa-check-circle' : 'fas fa-exclamation-circle'"></i> {{ errorMessage }}
          </div>
        </div>
      </div>

      <!-- 卡片底部：切换登录/注册 -->
      <div class="card-footer">
        <p v-if="!showRegister">
          还没有账户？
          <a href="#" class="switch-link" @click.prevent="togglePanel">立即注册！</a>
        </p>
        <p v-else>
          已有账户？
          <a href="#" class="switch-link" @click.prevent="togglePanel">马上登录！</a>
        </p>
      </div>
    </div>
  </div>
</template>

<script>
import { ref } from 'vue'
import { useRouter } from 'vue-router'
import axios from 'axios'

export default {
  name: 'Login',
  emits: ['login-success'],
  setup(props, { emit }) {
    const router = useRouter()
    const showRegister = ref(false)
    const loginForm = ref({ username: '', password: '' })
    const registerForm = ref({ username: '', nickname: '', password: '', confirmPassword: '' })
    const errorMessage = ref('')
    const isLoading = ref(false)
    const isSuccessMessage = ref(false) // 新增状态

    const togglePanel = () => {
      errorMessage.value = ''
      isLoading.value = false
      isSuccessMessage.value = false // 重置成功状态
      showRegister.value = !showRegister.value
      loginForm.value = { username: '', password: '' }
      registerForm.value = { username: '', nickname: '', password: '', confirmPassword: '' }
    }

    const handleLogin = async () => {
      if (!loginForm.value.username || !loginForm.value.password) {
        errorMessage.value = '请输入用户名和密码'
        isSuccessMessage.value = false // 确保是错误状态
        return
      }
      isLoading.value = true
      errorMessage.value = ''
      isSuccessMessage.value = false // 重置
      try {
        const response = await axios.post('/api/users/login', loginForm.value)
        const user = {
          id: response.data.id,
          username: response.data.username,
          nickname: response.data.nickname || response.data.username,
          avatar: response.data.avatar
        }
        localStorage.setItem('currentUser', JSON.stringify(user))
        emit('login-success', user.username)
        router.push('/chat')
      } catch (error) {
        console.error('登录错误:', error)
        errorMessage.value = error.response?.data?.message || '登录失败，请检查您的凭据或稍后再试'
        isSuccessMessage.value = false // 确保是错误状态
      } finally {
        isLoading.value = false
      }
    }

    const handleRegister = async () => {
      const { username, nickname, password, confirmPassword } = registerForm.value
      if (!username || !nickname || !password || !confirmPassword) {
        errorMessage.value = '所有字段均为必填项'
        isSuccessMessage.value = false // 确保是错误状态
        return
      }
      if (password !== confirmPassword) {
        errorMessage.value = '两次输入的密码不一致'
        isSuccessMessage.value = false // 确保是错误状态
        return
      }
      isLoading.value = true
      errorMessage.value = ''
      isSuccessMessage.value = false // 重置
      try {
        await axios.post('/api/users/register', { username, nickname, password })
        errorMessage.value = '注册成功！请使用您的新账户登录。'
        isSuccessMessage.value = true // 设置为成功状态
        showRegister.value = false
        loginForm.value.username = username;
        registerForm.value = { username: '', nickname: '', password: '', confirmPassword: '' }
      } catch (error) {
        console.error('注册错误:', error)
        errorMessage.value = error.response?.data?.message || '注册失败，可能是用户名已存在或服务器错误'
        isSuccessMessage.value = false // 确保是错误状态
      } finally {
        isLoading.value = false
      }
    }

    // Card hover 3D effect
    const handleCardMouseMove = (event) => {
      const card = event.currentTarget;
      const {width, height, left, top} = card.getBoundingClientRect();
      const x = event.clientX - left;
      const y = event.clientY - top;
      const rotateX = (y - height / 2) / (height/2) * -7;
      const rotateY = (x - width / 2) / (width/2) * 7;
      card.style.transform = `perspective(1000px) rotateX(${rotateX}deg) rotateY(${rotateY}deg) scale(1.03)`;
      card.style.transition = 'transform 0.1s linear';
    }

    const resetCardTransform = (event) => {
      const card = event.currentTarget;
      card.style.transform = 'perspective(1000px) rotateX(0deg) rotateY(0deg) scale(1)';
      card.style.transition = 'transform 0.5s cubic-bezier(0.23, 1, 0.32, 1)';
    }


    return {
      showRegister,
      loginForm,
      registerForm,
      errorMessage,
      isLoading,
      togglePanel,
      handleLogin,
      handleRegister,
      handleCardMouseMove,
      resetCardTransform,
      isSuccessMessage // 暴露给模板
    }
  }
}
</script>

<style scoped>
.login-container {
  display: flex;
  justify-content: center;
  align-items: center;
  min-height: 100vh;
  background: transparent;
  padding: 20px;
}

.artistic-card {
  width: 100%;
  max-width: 430px;
  background: rgba(25, 22, 60, 0.7);
  backdrop-filter: blur(18px) saturate(180%) brightness(1.1);
  border-radius: 30px;
  overflow: hidden;
  box-shadow: 0 25px 60px rgba(0, 0, 0, 0.4), 0 0 0 1.5px rgba(255, 255, 255, 0.12),
  inset 0 0 20px rgba(200, 180, 255, 0.1);
  border: 1px solid rgba(255, 255, 255, 0.2);
  animation: cardEntrance 1s cubic-bezier(0.165, 0.84, 0.44, 1) forwards;
  position: relative;
  transform-style: preserve-3d;
  transition: transform 0.5s cubic-bezier(0.23, 1, 0.32, 1);
}

.artistic-card::before {
  content: '';
  position: absolute;
  top: -50%; left: -50%;
  width: 200%; height: 200%;
  background: radial-gradient(circle, rgba(120, 80, 220, 0.25) 0%, rgba(120, 80, 220, 0) 60%);
  transform: rotate(0deg);
  transition: transform 1s ease-in-out;
  z-index: 0;
  pointer-events: none;
  animation: cardShine 15s infinite linear;
}

@keyframes cardShine {
  0% { transform: rotate(0deg) scale(1); }
  50% { transform: rotate(180deg) scale(1.2); }
  100% { transform: rotate(360deg) scale(1); }
}


@keyframes cardEntrance {
  from { opacity: 0; transform: translateY(70px) rotateX(-20deg) scale(0.9); }
  to { opacity: 1; transform: translateY(0) rotateX(0deg) scale(1); }
}

.card-header, .card-body, .card-footer {
  position: relative;
  z-index: 1;
}

.card-header {
  padding: 40px 35px 30px;
  text-align: center;
  background: rgba(0, 0, 0, 0.25);
  border-bottom: 1px solid rgba(255, 255, 255, 0.15);
  position: relative;
  overflow: hidden;
}

.card-header::after {
  content: '';
  position: absolute;
  top: 0; left: -100%;
  width: 100%; height: 3px;
  background: linear-gradient(90deg, transparent, rgba(173, 216, 230, 0.8), transparent);
  animation: headerShine 4s infinite ease-in-out;
}

@keyframes headerShine {
  0% { left: -100%; }
  50% { left: 100%; }
  100% { left: -100%; }
}

.card-header h1 {
  font-size: 2.2rem;
  font-weight: 700;
  margin-bottom: 10px;
  color: #f5f5f5;
  text-shadow: 0 0 10px rgba(255,255,255,0.3);
}

.card-header p {
  font-size: 1rem;
  color: rgba(230, 230, 255, 0.8);
}

.gradient-text {
  background: linear-gradient(90deg, #7F7FD5, #86A8E7, #91EAE4, #f72585);
  -webkit-background-clip: text;
  background-clip: text;
  background-size: 250% auto;
  color: transparent;
  animation: hueRotate 12s infinite linear, textShine 8s infinite alternate ease-in-out;
}

@keyframes textShine {
  0% { background-position: 0% 50%; }
  100% { background-position: 100% 50%; }
}


.card-body {
  padding: 35px 40px;
}

.form-container {
  display: flex;
  flex-direction: column;
  gap: 25px;
  position: relative;
  min-height: 260px; /* Adjusted for message box */
}

.form-panel {
  display: flex;
  flex-direction: column;
  gap: 25px;
  transition: opacity 0.5s ease-in-out, transform 0.5s cubic-bezier(0.68, -0.55, 0.265, 1.55);
  width: 100%;
}

.form-panel:not(.active-panel) {
  opacity: 0;
  transform: translateX(30px) scale(0.95);
  position: absolute;
  pointer-events: none;
}
.show-register-panel .form-panel:not(.active-panel) {
  transform: translateX(-30px) scale(0.95);
}


.input-group {
  position: relative;
}

.artistic-input {
  width: 100%;
  padding: 16px 22px 16px 55px;
  border: 1.5px solid rgba(255, 255, 255, 0.25);
  background: rgba(255, 255, 255, 0.1);
  border-radius: 14px;
  color: white;
  font-size: 1rem;
  transition: all 0.35s ease;
  caret-color: #4cc9f0;
  box-shadow: inset 0 1px 3px rgba(0,0,0,0.2);
}

.artistic-input::placeholder {
  color: rgba(255, 255, 255, 0.6);
}

.artistic-input:focus {
  outline: none;
  background: rgba(255, 255, 255, 0.18);
  border-color: transparent;
  box-shadow: 0 0 20px rgba(76, 201, 240, 0.6), 0 0 30px rgba(76, 201, 240, 0.4),
  inset 0 1px 3px rgba(0,0,0,0.1);
  animation: glow 1.5s infinite alternate;
}

.icon {
  position: absolute;
  left: 20px;
  top: 50%;
  transform: translateY(-50%);
  color: rgba(255, 255, 255, 0.7);
  font-size: 1.1rem;
  transition: color 0.3s ease, text-shadow 0.3s ease;
}

.artistic-input:focus + .icon {
  color: #4cc9f0;
  text-shadow: 0 0 8px #4cc9f0;
}

.artistic-button {
  padding: 16px;
  background: linear-gradient(90deg, #6A11CB, #2575FC);
  color: white;
  border: none;
  border-radius: 14px;
  font-size: 1.1rem;
  font-weight: 600;
  cursor: pointer;
  transition: all 0.3s ease;
  position: relative;
  overflow: hidden;
  box-shadow: 0 10px 20px rgba(47, 83, 206, 0.3);
  letter-spacing: 0.8px;
  text-transform: uppercase;
}
.artistic-button.register {
  background: linear-gradient(90deg, #F02FC2, #6094EA);
  box-shadow: 0 10px 20px rgba(225, 64, 181, 0.3);
}
.artistic-button::before {
  content: "";
  position: absolute;
  top: 0;
  left: -150%;
  width: 70%;
  height: 100%;
  background: linear-gradient(90deg, transparent, rgba(255,255,255,0.35), transparent);
  transform: skewX(-25deg);
  transition: left 0.7s ease-in-out;
}

.artistic-button:hover::before {
  left: 150%;
}


.artistic-button:hover:not(:disabled) {
  transform: translateY(-4px) scale(1.03);
  box-shadow: 0 15px 30px rgba(67, 97, 238, 0.4);
  filter: brightness(1.1);
}
.artistic-button.register:hover:not(:disabled) {
  box-shadow: 0 15px 30px rgba(247, 37, 133, 0.4);
}

.artistic-button:active:not(:disabled) {
  transform: translateY(-1px) scale(0.97);
  box-shadow: 0 6px 12px rgba(0,0,0, 0.25);
  filter: brightness(0.95);
}
.artistic-button:active:not(:disabled)::before {
  left: -200%;
}


.artistic-button:disabled {
  background: linear-gradient(90deg, #5a5a70, #404052);
  cursor: not-allowed;
  transform: none;
  box-shadow: none;
  opacity: 0.6;
}

.spinner {
  display: inline-block;
  width: 22px;
  height: 22px;
  border: 3.5px solid rgba(255, 255, 255, 0.3);
  border-radius: 50%;
  border-top-color: white;
  animation: spin 0.7s linear infinite;
  margin: 0 auto;
}

@keyframes spin {
  0% { transform: rotate(0deg); }
  100% { transform: rotate(360deg); }
}

.message-display-box { /* 通用样式 */
  padding: 12px 18px;
  border-radius: 10px;
  text-align: center;
  font-size: 0.95rem;
  margin-top: 8px;
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 10px;
  animation: fadeIn 0.3s ease;
}

.error-message-box {
  color: #ff9a8c;
  background-color: rgba(255, 100, 100, 0.15);
  border: 1px solid rgba(255, 100, 100, 0.35);
  text-shadow: 0 0 5px rgba(255,100,100,0.2);
}
.error-message-box i.fa-exclamation-circle {
  color: #ff7066;
}


.success-message-box {
  color: #a5d6a7;
  background-color: rgba(76, 175, 80, 0.15);
  border: 1px solid rgba(76, 175, 80, 0.35);
  text-shadow: 0 0 5px rgba(76,175,80,0.2);
}
.success-message-box i.fa-check-circle {
  color: #4CAF50;
}


.card-footer {
  padding: 30px;
  text-align: center;
  font-size: 0.95rem;
  color: rgba(230, 230, 255, 0.75);
  background: rgba(0, 0, 0, 0.15);
  border-top: 1px solid rgba(255, 255, 255, 0.1);
}

.switch-link {
  color: #6ac7e6;
  text-decoration: none;
  font-weight: 600;
  transition: all 0.3s ease;
  text-shadow: 0 0 3px rgba(106, 199, 230, 0.3);
}

.switch-link:hover {
  color: #f881b3;
  text-decoration: none;
  text-shadow: 0 0 8px #f881b3, 0 0 12px #f881b3;
}
</style>
